﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using OnWork.DataCenter.BLL.DataCenter;
using OnWork.DataCenter.DAL.DataCenter;
using SqlSugar;

namespace OnWork.DataCenter.Shared.Pages.DataSource
{
    public partial class DataBaseConfigView : ComponentBaseDataCenter
    {
        /// <summary>
        /// 依赖注入 提示信息
        /// </summary>
        [Inject]
        protected DSDataBaseBLL bll { get; set; }

        /// <summary>
        /// 数据库类型列表
        /// </summary>
        private IEnumerable<SelectedItem> DbTypeItems { get; set; }

        protected override void OnAfterRender(bool firstRender)
        {
            base.OnAfterRender(firstRender);
            if (firstRender)
            {
                var enums = Enum.GetNames(typeof(DbType));

                DbTypeItems = enums.Select(x => new SelectedItem() { Text = x, Value = x }).ToList();
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private async Task<QueryData<DataBaseConfigVO>> QueryAsync(QueryPageOptions options)
        {
            var result = await bll.QueryPagedListAsync(options.ToBaseQueryPageInput());
            //对象转换
            return result.ToQueryData<DataBaseConfigVO, DSDataBase>();
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        private async Task<bool> OnDeleteAsync(IEnumerable<DataBaseConfigVO> item)
        {
            var result = await bll.DeleteDataAsync(item.Select(x => x.ID).ToArray());

            return await ShowSqlReturnMsg(result);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="item"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        private async Task<bool> OnSaveAsync(DataBaseConfigVO item, ItemChangedType changedType)
        {
            //RESTfulResult<object> result;
            if (changedType == ItemChangedType.Update) // 更新
            {
                var result = await bll.UpdateDataAsync(item.Adapt<DSDataBase>());
                return await ShowSqlReturnMsg(result);
            }
            else //新增
            {
                var result = await bll.AddDataAsync(item.Adapt<DSDataBase>());
                return await ShowSqlReturnMsg(result);
            }
        }

        private BootstrapInput<string> bootstrapInput;

        private Dictionary<DbType, string> dictDbConns = new Dictionary<DbType, string>()
        {
            [DbType.MySql] = "server=localhost;Database=SqlSugar4xTest;Uid=root;Pwd=haosql;Allow Zero Datetime=True;",
            [DbType.Oracle] = "Data Source=localhost/orcl;User ID=system;Password=haha",
            [DbType.SqlServer] = "server=.;uid=sa;pwd=haosql;database=SQLSUGAR4XTEST;Encrypt=True;TrustServerCertificate=True;",
            [DbType.Access] = "Provider=Microsoft.ACE.OleDB.15.0;Data Source=\"+GetCurrentProjectPath+\"\\\\test.accdb",
            [DbType.PostgreSQL] = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres",
            [DbType.Sqlite] = "DataSource=c:\\database\\SqlSugar4xTest.sqlite",
            [DbType.QuestDB] = "host=localhost;port=8812;username=admin;password=quest;database=qdb;ServerCompatibilityMode=NoTypeLoading;",
            //达梦
            [DbType.Dm] = "Server=localhost; User Id=SYSDBA; PWD=SYSDBA;DATABASE=新DB",
            //人大金仓
            [DbType.Kdbndp] = "Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=SQLSUGAR4XTEST1",
        };

        /// <summary>
        /// 选择修改
        /// </summary>
        /// <param name="type"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private async Task OnSelectedItemChangedAsync(SelectedItem type, DataBaseConfigVO model)
        {
            //当更换数据类型时切换数据连接

            //获取原始字符串
            string connString = dictDbConns.GetValueOrDefault(model.Type);

            //修改控件的值 直接修改无反映
            if (!string.IsNullOrEmpty(connString))
            {
                bool isContain = dictDbConns.Values.Contains(model.ConnStr);
                if (string.IsNullOrEmpty(model.ConnStr) ||isContain) //如果是原始字符串则进行修改
                {
                    bootstrapInput.SetValue(connString);
                    bootstrapInput.SetDisable(false);
                }
            }

            await Task.CompletedTask;
        }

        /// <summary>
        /// 连接测试
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private async Task OnConnTestAsync(DataBaseConfigVO item)
        {
            //创建数据库对象
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = item.ConnStr,
                DbType = item.Type,
                IsAutoCloseConnection = true,
            });
            //判断是否是有效的
            Db.Ado.CommandTimeOut = 10; //数据库超时时间单位s 默认30
            var isok = Db.Ado.IsValidConnection();

            //成功
            if (isok)
            {
                await ToastService?.Success("数据库测试", "连接成功!");
            }
            else //失败
            {
                await ToastService?.Error("数据库测试", "连接失败!");
            }
        }
    }
}